package com.example.application;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.app.security.JwtUtils;
import com.example.app.vo.LoginRequest;
import com.example.app.vo.LoginResponse;
import com.example.infra.po.UsersPo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class AuthService {

    @Autowired
    private UsersService usersService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 账号密码登录
     */
    public LoginResponse loginByPassword(LoginRequest request) {
        // 查找用户（支持用户名、手机号、邮箱）
        UsersPo user = findUserByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!StringUtils.equals(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 生成token
        String token = jwtUtils.generateToken(user.getId(), user.getUsername());

        return LoginResponse.builder()
                .token(token)
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .email(user.getEmail())
                .build();
    }

    /**
     * 根据标识符查找用户
     */
    private UsersPo findUserByUsername(String username) {
        LambdaQueryWrapper<UsersPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UsersPo::getUsername, username)
                .or().eq(UsersPo::getEmail, username);
        return usersService.getOne(wrapper);
    }


    /**
     * 登出
     */
    public void logout(String token) {
        jwtUtils.logout(token);
    }

    /**
     * 刷新token
     */
    public LoginResponse refreshToken(String token) {
        String newToken = jwtUtils.refreshToken(token);
        Integer userId = jwtUtils.getUserIdFromToken(newToken);
        UsersPo user = usersService.getById(userId);

        return LoginResponse.builder()
                .token(newToken)
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .email(user.getEmail())
                .build();
    }
}
